package com.xiaorong.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;
import javax.persistence.PersistenceContext;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;

import com.xiaorong.dao.CommonDao;

@Repository
@Lazy
public class CommonDaoImpl implements CommonDao{
	
	@PersistenceContext
	protected EntityManager entityManager;

	@Override
	public Object find(Long id, String entity) {
		if(id != null){
			String jpql = "select obj from " + entity + " obj where obj.id = " + id;
			return entityManager.createQuery(jpql).setFlushMode(FlushModeType.COMMIT).getSingleResult();
		}
		return null;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Object> findAll(String entity) {
		String jpql = "select obj from " + entity + " obj";
		return entityManager.createQuery(jpql).setFlushMode(FlushModeType.COMMIT).getResultList();
	}

	@Override
	public boolean isExist(String entity, String property, String value) {
		String jpql = "select count(*) from " + entity + " obj where obj." + property + " = " + value.trim();
		System.out.println(jpql);
		Long count = entityManager.createQuery(jpql, Long.class).setFlushMode(FlushModeType.COMMIT).getSingleResult();
		
		return count > 0;
	}
	
	
	
}
